/**
 * 文件名：BaseCustomer.java
 * 全路径：com.xianshiyue.mi.BaseCustomer
 */
package cn.sharetraffic.mi.xiaomi;

import java.util.Map;

import cn.sharetraffic.mi.FindListener;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

/**
 * 功能：顾客<br>
 * 作者：蒋睿立<br> 
 * 时间：2016年6月27日<br> 
 * 版本：1.1<br>
 * 有货才log.info否则都log.debug
 */
public abstract class BaseMICustomer {

	private Logger log = Logger.getLogger(getClass());
	private FindListener onFindListener;
	private StringBuilder msg = new StringBuilder();
	private final Map<String, String> spec = new java.util.HashMap<>();

	public abstract void cost(JSONObject c);

	public JSONObject findGoods(Map<String, String> data) {
		JSONObject reValue = null;
		String str = "http://m.mi.com/v1/product/view";
		Connection conn = Jsoup.connect(str);
		Response resp = null;
		try {
			conn.timeout(5000); // 5秒超时
			conn.method(Method.POST);
			conn.ignoreContentType(true);
			conn.userAgent(
					"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36");
			conn.referrer("http://m.mi.com/1/");
			conn.data(data);
			resp = conn.execute();
			// 成功获取当前销售状态
			if (resp.statusCode() == 200 && resp.statusMessage().equalsIgnoreCase("ok")) {
				reValue = new JSONObject(resp.body());
			} else {
				log.warn("状态码:" + resp.statusCode() + ",状态值:" + resp.statusMessage());
			}
			if (onFindListener != null) {
				onFindListener.exactlyOnTime();
			}
		} catch (java.io.IOException e) {
			log.error(this.getClass().getName(), e);
			if (onFindListener != null) {
				onFindListener.timeout();
			}
		} catch (JSONException e) {
			if (resp == null) {
				log.error(this.getClass().getName(), e);
			}else {
				log.error(resp.body(), e);
			}
			if (onFindListener != null) {
				onFindListener.timeout();
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			if (onFindListener != null) {
				onFindListener.timeout();
			}
		}
		return reValue;
	}

	/**
	 * @return the onFindListener
	 */
	public FindListener getOnFindListener() {
		return onFindListener;
	}

	public abstract void giveUp(JSONObject c);

	public void put(String key, String value) {
		this.spec.put(key, value);
	}

	/**
	 * @param onFindListener
	 *            the onFindListener to set
	 */
	public void setOnFindListener(FindListener onFindListener) {
		this.onFindListener = onFindListener;
	}

	public abstract void shopping();

	protected void findGood() {
		JSONObject json = findGoods(spec);
		if (json == null) {
			return;
		}
		JSONObject data = json.optJSONObject("data");
		if (data == null) {
			log.warn("JSON没有data属性");
			return;
		}
		String name = data.optString("name");
		JSONArray commodityList = data.optJSONArray("commodity_list");
		if (commodityList == null || commodityList.length() == 0) {
			log.warn("JSON没有commodity_list属性");
			return;
		}
		for (int i = 0; i < commodityList.length(); i++) {
			msg.setLength(0);
			msg.append("================================================");
			msg.append("\r\n");
			msg.append(name);
			msg.append("\r\n");
			JSONObject c = commodityList.getJSONObject(i);
			String color = c.getString("icon_name");
			if (c.getBoolean("is_cos")) {
				msg.append(color);
				msg.append("-->没货");
				log.debug(msg.toString());
				c.put("mi_name", name);
				giveUp(c);
			} else {
				msg.append(color);
				msg.append("-->有货！！！  ");
				log.info(msg.toString());
				c.put("mi_name", name);
				cost(c);
			}
		}
	}

}
